package com.cow.framework.core.transaction;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

//@Configuration
public class TransactionConfig {

	@Bean
	public DataSourceTransactionManager transactionManager(DataSource dataSource) {
		System.out.println("TransactionManager 初始化");
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean
	public TransactionInterceptor customTransactionInterceptor(DataSourceTransactionManager transactionManager) {
		System.out.println("TransactionInterceptor 初始化");
		TransactionInterceptor ti = new TransactionInterceptor();
		ti.setTransactionManager(transactionManager);
		Properties properties = new Properties();
		properties.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
		properties.setProperty("query*", "PROPAGATION_REQUIRED,readOnly");
		properties.setProperty("add*", "PROPAGATION_REQUIRED");
		properties.setProperty("save*", "PROPAGATION_REQUIRED");		
		properties.setProperty("remove*", "PROPAGATION_REQUIRED");
		properties.setProperty("update*", "PROPAGATION_REQUIRED");
		properties.setProperty("modify*", "PROPAGATION_REQUIRED");
		
		ti.setTransactionAttributes(properties);
		return ti;
	}

	@Bean
	public BeanNameAutoProxyCreator transactionAutoProxy() {
		System.out.println("TransactionAutoProxy 初始化");
		BeanNameAutoProxyCreator transactionAutoProxy = new BeanNameAutoProxyCreator();
		// 使用jdk接口代理，不使用cglib代理
		transactionAutoProxy.setProxyTargetClass(false);
		transactionAutoProxy.setBeanNames(new String[] { "*Controller" });
		transactionAutoProxy.setInterceptorNames(new String[] { "customTransactionInterceptor" });
		return transactionAutoProxy;
	}

}